import React, { Component } from 'react'
import axios from 'axios'
import storage from '../Utils/storage'
import '../css/Login.css'
import { Button, Form, Input } from 'antd'
import { connect } from 'react-redux'
import { setUserTokenInfo } from '../actions/userAction'

const FormItem = Form.Item

class Login extends Component {
    constructor (props) {
        super(props)
        this.state = {
            nickname : ''
        }
        this.formRef = React.createRef()
    }


    handleSubmit =()=>{ debugger
        const {dispatch} = this.props
        const form = this.formRef.current
        const username = form.getFieldValue("username")
        const password = form.getFieldValue("password")

        //编辑头文件，通过头文件解决跨域问题
        let config = {headers:{'Content-Type': 'application/json'},withCredentials:true}
        //进行后台请求
        axios({
            method: 'post',
            url:'http://localhost/mall-basic-service/login/jwt/login/login',
            params:{
                username: username,
                password: password
            }
        },config).then((response)=>{
            //登录成功
            const code = response.data.code
            if(code === 200){
                //先删除
                storage.remove("token")
                //重新复制
                storage.set("token",response.data);
                dispatch(setUserTokenInfo(response.data))
                this.setState({
                    nickname :response.data
                })
                window.location.reload()
            }
        }).catch(function (error) {
        })
    };

  render () {
    return (
      <div className="loginDiv" >
          <h2>用户登录界面</h2>
          <Form ref={this.formRef}>
              <label>
                  <FormItem label="用户名: " name={'username'}>
                  <Input type="text" />
                  </FormItem>
              </label>
              <br/>
              <label>
                  <FormItem label='密 码' name={'password'}>
                      <Input type="password" />
                  </FormItem>
              </label>
              <br/>
              <Button  className="btn btn-primary" onClick={this.handleSubmit}> 登录 </Button> &emsp;
              <Button  className="btn btn-primary"> 重置 </Button>
          </Form>
      </div>
    )
  }
}
const mapStateToProps = (state) =>{
    return {
        carts: state.get('cartNum'),
        userTokenInfo: state.get('userTokenInfo'),
    }
}
export default connect(mapStateToProps)(Login)
